package com.hejian.android.a72ggametools.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

import com.hejian.android.a72ggametools.bean.User;
import com.hejian.android.a72ggametools.database.DatabaseOpenHelper;

/**
 * Created by Administrator on 2016/1/20.
 */
public class UserInteraction {
    private DatabaseOpenHelper dbHelper;
    private Context context;

    public UserInteraction(Context context) {
        dbHelper = new DatabaseOpenHelper(context);
        this.context = context;
    }

    public String login(String userName, String password) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(true, "users", new String[]{"username", "password", "nickname"}, "username=? and" +
                " password=?", new String[]{userName, password}, null, null, null, null);
        if (cursor != null && cursor.getCount() != 0) {
            cursor.moveToNext();
            String nickName = cursor.getString(cursor.getColumnIndex("nickname"));
            cursor.close();
            return nickName;
        } else {
            Toast.makeText(context, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
        return null;
    }

    public boolean register(User user) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(true, "users", new String[]{"username"}, "username=?",
                new String[]{user.getUserName()}, null, null, null, null);
        if (cursor == null || cursor.getCount() == 0) {
            ContentValues values = new ContentValues();
            values.put("username", user.getUserName());
            values.put("password", user.getPassword());
            values.put("nickname", user.getNickName());
            db.insert("users", null, values);
            cursor.close();
            return true;
        } else {
            Toast.makeText(context, "您输入的用户名已存在", Toast.LENGTH_SHORT).show();
        }
        return false;

    }


}
